<template>
  <div class="image-generator-tabs">
    <a-card class="generator-card" :bordered="false">
      <template #title>
        <div class="title">
          <span>✨ 多功能图片生成器 ✨</span>
        </div>
      </template>

      <a-tabs v-model:activeKey="activeTab" centered animated>
        <a-tab-pane key="wallpaper" tab="壁纸生成 🖼️">
          <!-- 壁纸生成器内容 -->
          <div class="tab-content">
            <div class="controls">
              <a-form layout="vertical">
                <a-form-item label="设备类型 📱💻">
                  <a-select v-model:value="wallpaperParams.method" placeholder="选择设备类型">
                    <a-select-option value="pc">电脑端 💻</a-select-option>
                    <a-select-option value="mobile">手机端 📱</a-select-option>
                    <a-select-option value="zsy">自动判断 🔄</a-select-option>
                  </a-select>
                </a-form-item>

                <a-form-item label="壁纸分类 🏷️">
                  <a-radio-group v-model:value="wallpaperParams.lx" button-style="solid">
                    <a-radio-button value="suiji">随机 🎲</a-radio-button>
                    <a-radio-button value="dongman">动漫 🎭</a-radio-button>
                    <a-radio-button value="fengjing">风景 🏞️</a-radio-button>
                    <a-radio-button value="meizi">美女 👩</a-radio-button>
                  </a-radio-group>
                </a-form-item>

                <a-form-item>
                  <a-button type="primary" @click="generateWallpaper" :loading="wallpaperLoading" block>
                    生成新壁纸 🖼️
                  </a-button>
                </a-form-item>
              </a-form>
            </div>

            <div class="image-container" v-if="wallpaperData">
              <div class="image-wrapper">
                <a-skeleton active :loading="wallpaperLoading" :paragraph="{ rows: 10 }" v-if="wallpaperLoading"></a-skeleton>
                <img
                  v-else
                  :src="wallpaperData.imgurl"
                  alt="生成的壁纸"
                  class="generated-image"
                  @load="wallpaperLoaded = true"
                  v-show="wallpaperLoaded"
                />
                <div class="image-info" v-if="!wallpaperLoading && wallpaperLoaded">
                  <a-tag color="blue">{{ wallpaperData.width }}x{{ wallpaperData.height }}</a-tag>
                  <a-tag color="green">{{ getWallpaperCategoryName(wallpaperParams.lx) }}</a-tag>
                  <a-tag color="purple">{{ getDeviceName(wallpaperParams.method) }}</a-tag>
                </div>
              </div>

              <a-divider>
                <span class="divider-text">🔗 壁纸链接 🔗</span>
              </a-divider>

              <div class="url-container">
                <a-input-group compact>
                  <a-input
                    v-model:value="wallpaperData.imgurl"
                    readonly
                    class="url-input"
                  />
                  <a-tooltip title="复制链接">
                    <a-button @click="copyUrl(wallpaperData.imgurl)" type="primary">
                      <template #icon><copy-outlined /></template>
                    </a-button>
                  </a-tooltip>
                </a-input-group>
              </div>

              <div class="action-buttons">
                <a-button type="primary" @click="downloadImage(wallpaperData.imgurl, 'wallpaper')" :disabled="wallpaperLoading || !wallpaperLoaded">
                  <template #icon><download-outlined /></template>
                  下载壁纸
                </a-button>
                <a-button @click="shareImage(wallpaperData.imgurl, '精美壁纸')" :disabled="wallpaperLoading || !wallpaperLoaded">
                  <template #icon><share-alt-outlined /></template>
                  分享壁纸
                </a-button>
              </div>
            </div>

            <div class="empty-state" v-else>
              <a-empty description="点击生成按钮获取壁纸" />
            </div>
          </div>
        </a-tab-pane>

        <a-tab-pane key="avatar" tab="头像生成 👤">
          <!-- 头像生成器内容 -->
          <div class="tab-content">
            <div class="controls">
              <a-form layout="vertical">
                <a-form-item label="设备类型 📱💻">
                  <a-select v-model:value="avatarParams.method" placeholder="选择设备类型">
                    <a-select-option value="pc">电脑端 💻</a-select-option>
                    <a-select-option value="mobile">手机端 📱</a-select-option>
                    <a-select-option value="zsy">自动判断 🔄</a-select-option>
                  </a-select>
                </a-form-item>

                <a-form-item label="头像类型 👤">
                  <a-radio-group v-model:value="avatarParams.lx" button-style="solid">
                    <a-radio-button value="a1">男头 👨</a-radio-button>
                    <a-radio-button value="b1">女头 👩</a-radio-button>
                    <a-radio-button value="c1">动漫头像 🎭</a-radio-button>
                    <a-radio-button value="c2">动漫女头 👸</a-radio-button>
                    <a-radio-button value="c3">动漫男头 🧙‍♂️</a-radio-button>
                  </a-radio-group>
                </a-form-item>

                <a-form-item>
                  <a-button type="primary" @click="generateAvatar" :loading="avatarLoading" block>
                    生成新头像 👤
                  </a-button>
                </a-form-item>
              </a-form>
            </div>

            <div class="image-container" v-if="avatarData">
              <div class="image-wrapper">
                <a-skeleton active :loading="avatarLoading" :paragraph="{ rows: 8 }" v-if="avatarLoading"></a-skeleton>
                <img
                  v-else
                  :src="avatarData.imgurl"
                  alt="生成的头像"
                  class="generated-image avatar-image"
                  @load="avatarLoaded = true"
                  v-show="avatarLoaded"
                />
                <div class="image-info" v-if="!avatarLoading && avatarLoaded">
                  <a-tag color="blue">{{ avatarData.width }}x{{ avatarData.height }}</a-tag>
                  <a-tag color="green">{{ getAvatarTypeName(avatarParams.lx) }}</a-tag>
                </div>
              </div>
              <a-card title="提示">
                <a-typography-paragraph>
                  * 头像要上传要自己下点载，有什么bug请联系
                  <a href="https://blog.csdn.net/weixin_74550669?spm=1000.2115.3001.10640" target="_blank">我</a>。
                </a-typography-paragraph>
                <a-typography-paragraph v-for="spaceLevel in spaceLevelList">
                  {{ spaceLevel.text }}： 大小 {{ formatSize(spaceLevel.maxSize) }}， 数量
                  {{ spaceLevel.maxCount }}
                </a-typography-paragraph>
              </a-card>
<!--              <a-divider>-->
<!--                <span class="divider-text">🔗 头像链接 🔗</span>-->
<!--              </a-divider>-->

<!--              <div class="url-container">-->
<!--                <a-input-group compact>-->
<!--                  <a-input-->
<!--                    v-model:value="avatarData.imgurl"-->
<!--                    readonly-->
<!--                    class="url-input"-->
<!--                  />-->
<!--                  <a-tooltip title="复制链接">-->
<!--                    <a-button @click="copyUrl(avatarData.imgurl)" type="primary">-->
<!--                      <template #icon><copy-outlined /></template>-->
<!--                    </a-button>-->
<!--                  </a-tooltip>-->
<!--                </a-input-group>-->
<!--              </div>-->


              <div class="action-buttons">
                <a-button type="primary" @click="downloadImage(avatarData.imgurl, 'avatar')" :disabled="avatarLoading || !avatarLoaded">
                  <template #icon><download-outlined /></template>
                  下载头像
                </a-button>
                <a-button @click="shareImage(avatarData.imgurl, '精美头像')" :disabled="avatarLoading || !avatarLoaded">
                  <template #icon><share-alt-outlined /></template>
                  分享头像
                </a-button>
              </div>
            </div>

            <div class="empty-state" v-else>
              <a-empty description="点击生成按钮获取头像" />
            </div>
          </div>
        </a-tab-pane>
        <a-tab-pane key="meme" tab="生成表情包🎭">
<MemeContainerPage />


        </a-tab-pane>
      </a-tabs>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { message } from 'ant-design-vue';
import axios from 'axios';
import { CopyOutlined, DownloadOutlined, ShareAltOutlined } from '@ant-design/icons-vue';
import { formatSize } from '@/utils/index.js'
import MemeContainerPage from '@/pages/generator/MemeContainerPage.vue'
import * as https from 'node:https'

// 选项卡状态
const activeTab = ref('wallpaper');

// 壁纸生成器状态
const wallpaperParams = reactive({
  method: 'pc',
  lx: 'suiji',
  format: 'json'
});
const wallpaperData = ref(null);
const wallpaperLoading = ref(false);
const wallpaperLoaded = ref(false);

// 头像生成器状态
const avatarParams = reactive({
  method: 'pc',
  lx: 'c1',
  format: 'json'
});
const avatarData = ref(null);
const avatarLoading = ref(false);
const avatarLoaded = ref(false);

// 自定义生成器状态
const customParams = reactive({
  apiType: 'wallpaper',
  method: 'pc',
  wallpaperType: 'suiji',
  avatarType: 'c1',
  format: 'json'
});
const customData = ref(null);
const customLoading = ref(false);
const customLoaded = ref(false);

// 获取壁纸分类名称
const getWallpaperCategoryName = (lx) => {
  const categories = {
    'suiji': '随机壁纸',
    'dongman': '动漫壁纸',
    'fengjing': '风景壁纸',
    'meizi': '美女壁纸'
  };
  return categories[lx] || '随机壁纸';
};

// 获取头像类型名称
const getAvatarTypeName = (lx) => {
  const types = {
    'a1': '男头',
    'b1': '女头',
    'c1': '动漫头像',
    'c2': '动漫女头',
    'c3': '动漫男头'
  };
  return types[lx] || '动漫头像';
};

// 获取设备名称
const getDeviceName = (method) => {
  const devices = {
    'pc': '电脑端',
    'mobile': '手机端',
    'zsy': '自适应'
  };
  return devices[method] || '电脑端';
};

// 生成壁纸方法
const generateWallpaper = async () => {
  wallpaperLoading.value = true;
  wallpaperLoaded.value = false;

  try {
    const response = await axios.get('https://api.btstu.cn/sjbz/api.php', {
      params: wallpaperParams,

    });

    wallpaperData.value = response.data;
    message.success('壁纸生成成功 🎉');
  } catch (error) {
    console.error('获取壁纸失败:', error);
    message.error('获取壁纸失败，请重试 😢');
  } finally {
    wallpaperLoading.value = false;
  }
};

// 生成头像方法
const generateAvatar = async () => {
  avatarLoading.value = true;
  avatarLoaded.value = false;

  try {
    const response = await axios.get('https://api.btstu.cn/sjtx/api.php', {
      params: avatarParams
    });

    avatarData.value = response.data;
    message.success('头像生成成功 🎉');
  } catch (error) {
    console.error('获取头像失败:', error);
    message.error('获取头像失败，请重试 😢');
  } finally {
    avatarLoading.value = false;
  }
};

// 生成自定义图片方法
const generateCustom = async () => {
  customLoading.value = true;
  customLoaded.value = false;

  try {
    const apiUrl = customParams.apiType === 'wallpaper'
      ? 'https://api.btstu.cn/sjbz/api.php'
      : 'https://api.btstu.cn/sjtx/api.php';

    const params = {
      method: customParams.method,
      format: customParams.format,
      lx: customParams.apiType === 'wallpaper' ? customParams.wallpaperType : customParams.avatarType
    };

    const response = await axios.get(apiUrl, { params });

    customData.value = response.data;
    message.success('图片生成成功 🎉');
  } catch (error) {
    console.error('获取图片失败:', error);
    message.error('获取图片失败，请重试 😢');
  } finally {
    customLoading.value = false;
  }
};

// 复制URL方法
const copyUrl = (url) => {
  if (url) {
    navigator.clipboard.writeText(url)
      .then(() => {
        message.success('链接已复制到剪贴板 📋');
      })
      .catch(() => {
        message.error('复制失败，请手动复制 ❌');
      });
  }
};

// 下载图片方法
const downloadImage = (url, type) => {
  if (url) {
    const link = document.createElement('a');
    link.href = url;
    link.download = `${type}-${Date.now()}.jpg`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    message.success('图片下载已开始 ⬇️');
  }
};

// 分享图片方法
const shareImage = (url, title) => {
  if (url) {
    if (navigator.share) {
      navigator.share({
        title: title,
        text: `看看这张精美的${title}！`,
        url: url,
      })
        .then(() => message.success('分享成功 🎉'))
        .catch((error) => {
          console.error('分享失败:', error);
          message.error('分享失败 ❌');
        });
    } else {
      copyUrl(url);
      message.info('您的浏览器不支持分享功能，已复制链接 🔗');
    }
  }
};

// 初始加载时生成壁纸
generateWallpaper();
</script>

<style scoped>
.image-generator-tabs {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
}

.generator-card {
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  background: linear-gradient(to bottom, #ffffff, #f9f9f9);
}

.title {
  font-size: 1.8rem;
  text-align: center;
  background: linear-gradient(45deg, #ff7676, #5662f6);
  -webkit-background-clip: text;
  background-clip: text;
  color: #1890ff;
  font-weight: bold;
  padding: 8px 0;
}

.tab-content {
  padding: 16px 0;
}

.controls {
  margin-bottom: 24px;
  background-color: rgba(245, 245, 245, 0.6);
  padding: 16px;
  border-radius: 12px;
}

.image-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-top: 20px;
}

.image-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.generated-image {
  max-width: 100%;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  transition: all 0.4s ease;
}

.generated-image:hover {
  transform: scale(1.02);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
}

.avatar-image {
  max-width: 300px;
  border-radius: 50%;
}

.image-info {
  display: flex;
  justify-content: center;
  gap: 8px;
  margin-top: 8px;
}

.divider-text {
  font-size: 14px;
  color: #666;
}

.url-container {
  margin: 0 auto;
  width: 100%;
}

.url-input {
  font-family: monospace;
  color: #1890ff;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 8px;
}

.empty-state {
  padding: 60px 0;
}

.custom-generator {
  margin-bottom: 20px;
}

@media (max-width: 576px) {
  .image-generator-tabs {
    padding: 10px;
  }

  .title {
    font-size: 1.4rem;
  }

  .action-buttons {
    flex-direction: column;
    gap: 8px;
  }
}
</style>
